package cn.cvs.controller;

import cn.cvs.pojo.SysRole;
import cn.cvs.pojo.SysUser;
import cn.cvs.service.SysRoleServlce;
import cn.cvs.service.SysUserServlce;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping(value = "/user")
public class UserController {

    @Autowired
    private SysUserServlce sysUserServlce;
    @Autowired
    private SysRoleServlce sysRoleServlce;

    @GetMapping(value = "/list")
    public  String list(Model model, String queryRealName,Integer queryRoleId,Integer pageIndex){


        Integer pageSize = 3;
        Integer startIndex = 0;

        if (pageIndex != null){
            startIndex = (pageIndex-1)*pageSize;
        }


        List<SysUser> list = sysUserServlce.list(queryRealName,queryRoleId,startIndex,pageSize);

        model.addAttribute("list",list);
        //查询角色信息 roLeList
        List<SysRole> roleList = sysRoleServlce.list();
        model.addAttribute("roleList",roleList);

//        int totalCount = sysUserServlce.count(queryRealName, queryRoleId);


//        model.addAttribute("totalCount",totalCount);



        return "sysUser/list";
    }

    @PostMapping(value = "/login")
    public String login(Model model, HttpServletRequest request, String account, String password){

        SysUser sysUser =sysUserServlce.login(account, password);


        //用户名或者密码不正确
        if (sysUser == null){
            model.addAttribute("error","用户名或者密码不正确");

            return "login";
        }

        request.getSession().setAttribute("userSession",sysUser);

        return "redirect:/main";
    }


    @GetMapping(value = "/logout")
    public String logout(HttpServletRequest request){
        request.getSession().removeAttribute("userSession");
        return "redirect:/login";
    }


}
